import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { asyncRoutes, constantRoutes } from '@/router'

export const usePermissionStore = defineStore('permission', () => {
  // 路由列表
  const routes = ref<RouteRecordRaw[]>([])
  
  // 侧边栏菜单
  const sidebarRoutes = ref<RouteRecordRaw[]>([])

  /**
   * 根据角色生成可访问路由
   */
  const generateRoutes = async (roles: string[]): Promise<RouteRecordRaw[]> => {
    let accessedRoutes: RouteRecordRaw[]
    
    if (roles.includes('admin')) {
      // 管理员拥有所有权限
      accessedRoutes = asyncRoutes || []
    } else {
      // 根据权限过滤路由
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
    }
    
    // 设置路由
    routes.value = constantRoutes.concat(accessedRoutes)
    sidebarRoutes.value = routes.value
    
    return accessedRoutes
  }

  /**
   * 根据权限过滤异步路由
   */
  const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]): RouteRecordRaw[] => {
    const res: RouteRecordRaw[] = []
    
    routes.forEach(route => {
      const tmp = { ...route }
      if (hasPermission(roles, tmp)) {
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
        res.push(tmp)
      }
    })
    
    return res
  }

  /**
   * 检查是否有权限
   */
  const hasPermission = (roles: string[], route: RouteRecordRaw): boolean => {
    if (route.meta && route.meta.roles) {
      return roles.some(role => (route.meta!.roles as string[]).includes(role))
    }
    
    if (route.meta && route.meta.perms) {
      // TODO: 这里需要根据用户的具体权限来判断
      // 暂时返回true，后续完善权限判断逻辑
      return true
    }
    
    return true
  }

  return {
    routes,
    sidebarRoutes,
    generateRoutes,
  }
})
